#include <ChannelManager.h>
#include <csp_debug.h>
#include <csp_macros.h>
#include <csp_shared_types.h>
#include <csp_protocol_msg.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <Channel.h>
#include <pthread.h>
#include <map>

using namespace std;

ChannelManager::ChannelManager()
{
	if( pthread_mutex_init(&chan_man_lock, NULL) ){
		perror("channel manager could not init lock.");
		exit(-1);
	}
	memset(channel_db, 0, sizeof(Channel*)*MAX_CHANNELS);
}

ChannelManager::~ChannelManager()
{
}


	Channel*
ChannelManager::GetChannel(long type, long id)
{
	//printf("ChannelManager:lock\n");
	pthread_mutex_lock (&chan_man_lock);
	Channel *channel=NULL;
/*
	map<long, Channel*> *channel_db;
	Channel *channel;

	switch(type) {
		case ONE2ONE_CHANNEL:
			channel_db = &one2one;
			break;
		case ANY2ONE_CHANNEL:
			channel_db = &any2one;
			break;
		case ONE2ANY_CHANNEL:
			channel_db = &one2any;
			break;
		case ANY2ANY_CHANNEL:
			channel_db = &any2any;
			break;
		default:
			printf("Unknown channeltype (%lX) with id=%lX.\n", type, id);
			exit(-1);
			break;
	}

	if(channel_db->find(id) == channel_db->end()){
		channel_db->insert(pair<long, Channel*>(id, new Channel(type, id)));
	}

	channel = (*channel_db)[id];
*/
	
	for(int i=0; i < MAX_CHANNELS; i++){
		if( NULL == channel_db[i] )	{
			channel = new Channel(type, id);	
			channel_db[i] = channel;
			goto found;
		}else if( id == channel_db[i]->GetID() ){
			channel = channel_db[i];	
			goto found;
		}
	}

	if( !channel ){
		perror("Maximum number of channels has been reached!\n");
		exit(-1);
	}

found:
	pthread_mutex_unlock (&chan_man_lock);
	//printf("ChannelManager:unlock\n");
	return channel;
}


ChannelManager* ChannelManager::pinstance = 0;// initialize pointer

	ChannelManager* 
ChannelManager::Instance () 
{
	if (pinstance == 0)  // is it the first call?
	{  
		pinstance = new ChannelManager(); // create sole instance
	}
	return pinstance; // address of sole instance
}


